package com.cdbkj.cloud.pos;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.dawn.cloud.pos.drive.hardware.SwipeCardService;


public class SwipeCardTest extends Activity {
    private TextView mTextView;
    private LocalBroadcastManager mBroadcastManager;
    private HardwareBroadcastReceiver mReceiver;


    private String card_no_info = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.swipe_card_test);

        mTextView = (TextView) findViewById(R.id.swipe_card_message);
        mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());

        mBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SwipeCardService.ACTION_SWIPE_CARD);
        mReceiver = new HardwareBroadcastReceiver();
        mBroadcastManager.registerReceiver(mReceiver, intentFilter);

        findViewById(R.id.start).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SwipeCardService.open(SwipeCardTest.this);
            }
        });

        findViewById(R.id.clear).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mTextView.setText("");
            }
        });

        findViewById(R.id.state).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        findViewById(R.id.close).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SwipeCardService.close(SwipeCardTest.this);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SwipeCardService.close(SwipeCardTest.this);
        mBroadcastManager.unregisterReceiver(mReceiver);
    }

    class HardwareBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (SwipeCardService.ACTION_SWIPE_CARD.equals(action)) {
                if(SwipeCardService.getReceiverData(intent)!=null){
                    card_no_info = SwipeCardService.getReceiverData(intent);
                    mTextView.append(card_no_info);
                }
                mTextView.append("\n");
            }
        }
    }
}
